<?php
class Manager_UserPermission
{
	const PERMISSION_ADMIN 	= 'admin';
	const PERMISSION_USER	= 'user';
	const PERMISSION_GUEST 	= 'guest';
	
	public static function initialize()
	{
		$names = array(self::PERMISSION_ADMIN, self::PERMISSION_GUEST, self::PERMISSION_USER);
		
		$criteria = new Criteria();
		
		// update users permissions table
		try {
			foreach ($names as $name) {
				$criteria->clear();
				$criteria->add(UserspermissionsPeer::NAME, $name, Criteria::EQUAL);
				
				if (UserspermissionsPeer::doCount($criteria) === 0) {
					// add to database missing reqest statuses
					$permission = new Userspermissions();
					$permission->setName($name);
					$permission->save();
				}
			}
		} catch (Exception $e) {
			throw new Exception('Preferences groups could not be initialized in the DB. ' . $e->getMessage());
		}
	}
	
	/**
	 * 
	 * @return Userspermissions
	 */
	public static function getAdmin()
	{
		$criteria = new Criteria();
		$criteria->add(UserspermissionsPeer::NAME, self::PERMISSION_ADMIN, Criteria::EQUAL);
		
		$admin = UserspermissionsPeer::doSelectOne($criteria);
		
		if (empty($admin)) {
			self::initialize();
		}
		
		return UserspermissionsPeer::doSelectOne($criteria);
	}
	
	//TODO: getUser, getModerator...
}